package edu.ynu.e_platform.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import edu.ynu.e_platform.dao.UserDao;
import edu.ynu.e_platform.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author manwen Yang
 */
@Component
public class TokenUtils {

    private static UserDao staticUserDao;

    @Resource
    private UserDao userdao;

    @PostConstruct
    public void setUserService(){
        staticUserDao = userdao;
    }

    public static String genToken(Long userId, String password){
        return JWT.create().withAudience(String.valueOf(userId))
                .withExpiresAt(DateUtil.offsetHour(new Date(), 2)) //2小时后token过期
                .sign(Algorithm.HMAC256(password));
    }

    /**
     * 获取当前登录的用户信息
     */
    public static User getCurrentUser(){

        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String token = request.getHeader("token");
            if(StrUtil.isNotBlank(token)){
                String userId = JWT.decode(token).getAudience().get(0);
                return staticUserDao.getReferenceById(Long.valueOf(userId));
            }
        }catch (Exception e) {
            return null;
        }

        return null;
    }
}
